package com.lfz.demo.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lfz.demo.entity.User;
import com.lfz.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author lfz
 * @date 2025/3/3 11:02
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 认证逻辑（关键改造：支持用户名/手机号登录）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = token.getPrincipal().toString(); // 登录凭证（用户名或手机号）

        // 1. 先尝试通过用户名查询
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        usernameQuery.eq("username", principal);
        User user = userService.getOne(usernameQuery);

        // 2. 若用户名未找到，尝试通过手机号查询
        if (user == null) {
            QueryWrapper<User> phoneQuery = new QueryWrapper<>();
            phoneQuery.eq("phone", principal);
            user = userService.getOne(phoneQuery);
        }

        // 3. 账户不存在时抛出异常
        if (user == null) {
            throw new UnknownAccountException("用户名或手机号不存在");
        }

        // 4. 返回认证信息（密码由Shiro自动校验，需与用户表中的密码一致）
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName()); // 返回真实密码
    }

    /**
     * 授权逻辑（保持不变，按需实现）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // TODO: 这里添加角色/权限授权逻辑（如从数据库获取用户角色）
        // authorizationInfo.addRoles(user.getRoles());
        // authorizationInfo.addStringPermissions(user.getPermissions());
        return authorizationInfo;
    }
}
